#include "lnlist.h"

LnList createLnList(void)
{
    LnList list;
    list = (LnList) malloc(sizeof(struct lnList));
    if (list == NULL)
    {
        return NULL;
    }
    
    list->head = (PNode) malloc(sizeof(struct LNode));
    if (list->head == NULL)
    {
        free(list);
        return NULL;
    }
    
    list->head->link = NULL;
    list->rear = list->head;
    list->length = 0;
    
    return list;
}

POSITION locateVertexLnList(LnList list, ELEMTYPE x)
{
    POSITION p;
    
    if (list == NULL)
    {
        return NULL;
    }
    
    p = list->head->link;

    while (p != NULL && p->info != x)
    {
        p = p->link;
    }
   
    return p;
}

int insertPostLnList(LnList list, POSITION p, ELEMTYPE x)
{
    PNode q;

    if (list == NULL || p == NULL)
    {
        return 0;
    }

    q = (PNode) malloc(sizeof(struct LNode));
    
    if (q != NULL)
    {
        q->info = x;
        q->link = p->link;
        p->link = q;
        list->length++;
        return 1;
    }

    return -1;
}

int insertPreLnList(LnList list, POSITION p, ELEMTYPE x)
{
    PNode q, l;

    if (list == NULL || p == NULL)
    {
        return 0;
    }

    q = (PNode) malloc(sizeof(struct LNode));
    
    if (q != NULL)
    {
        q->info = x;
        l = list->head;

        while (l->link != p && l != NULL)
        {
            l = l->link;
        }
        if (l != NULL)
        {
            q->link = l->link;
            l->link = q;
            list->length++;
            return 1;
        }
    }

    return -1;
}

int appendElemLnList(LnList list, ELEMTYPE x)
{
    PNode p;

    if (list == NULL)
    {
        return -1;
    }
    
    p = (PNode) malloc(sizeof(struct LNode));
    
    if (p != NULL)
    {
        p->info = x;
        p->link = NULL;
        list->rear->link = p;
        
        list->rear = p;
        list->length++;
        return 1;
    }
    
    return 0;
}

void printLnList(LnList list)
{
    POSITION p;
    int i;
    
    if (list == NULL)
    {
        return ;
    }

    p = list->head->link;
    i = 0;

    while (p != NULL)
    {
        printf("node[%d] = %d, address = %u\n", i++, p->info, p);
        p = p->link;
    }
}

void destroyLnList(LnList *list)
{
    PNode p, q;

    if (*list == NULL)
    {
        return ;
    }

    p = (*list)->head;
    while (p != NULL)
    {
        q = p;
        p = p->link;
        free(q);
    }
    
    free(*list);
    *list = NULL;
}

int lengthLnList(LnList list)
{
    if (list != NULL)
    {
        return list->length;
    }
    return -1;
}
